package com.jrx.anytxn.transaction.service.impl;
import java.net.SocketException;
import java.util.Date;
import com.google.common.collect.Lists;

import com.jrx.anytxn.common.uitl.*;
import com.jrx.anytxn.customer.constant.BankCardConstant;
import com.jrx.anytxn.customer.constant.CustomerConstant;
import com.jrx.anytxn.customer.dto.bankcardinfo.BankCardRes;
import com.jrx.anytxn.customer.entity.CmCustomerBankcardInfo;
import com.jrx.anytxn.customer.entity.CmCustomerFirstLevel;
import com.jrx.anytxn.customer.entity.CmCustomerSecondLevel;
import com.jrx.anytxn.customer.entity.TlMarketingRecord;
import com.jrx.anytxn.customer.service.IBankCardService;
import com.jrx.anytxn.customer.service.ICustomerService;
import com.jrx.anytxn.feign.gateway.request.*;
import com.jrx.anytxn.param.dto.system.SystemParameterRes;
import com.jrx.anytxn.param.entity.PrCodeTable;
import com.jrx.anytxn.param.service.system.ICodeTableService;
import com.jrx.anytxn.param.service.system.ISystemParameterService;
import com.jrx.anytxn.param.utils.BizTypeProducts;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.TlDisbursementLog;
import com.jrx.anytxn.transaction.entity.TlPaymentLog;
import com.jrx.anytxn.transaction.entity.TlRefundLog;
import com.jrx.anytxn.transaction.entity.TlSmsLog;
import com.jrx.anytxn.transaction.pojo.DailyAccount;
import com.jrx.anytxn.transaction.service.IDealGatewayService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @program: anytxn-cf-transaction
 * @description:
 * @author: xiaoyu.jing
 * @date: 2019-11-25 20:45
 **/
@Service
public class DealGatewayServiceImpl implements IDealGatewayService {
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private ISystemParameterService systemParameterService;
    @Autowired
    private IBankCardService bankCardService;
    @Autowired
    private ICodeTableService codeTableService;

    /**
     * 构建单笔代收请求
     * @param log
     * @return
     */
    @Override
    public String buildCollectReq(TlPaymentLog log) throws Exception {
        CmCustomerFirstLevel res =customerService.getFirstLevelByCondition(log.getCustomerId(),
                log.getOrganizationId(),log.getTenantId());

        CmCustomerSecondLevel secondLevel =  customerService.getSecondByChannelAndCustomerIdAndTensnId(log.getChannel(), log.getCustomerId(), log.getTenantId(), log.getProductId());


        PaymentRequest06 req = new PaymentRequest06();
        req.setServiceId(TransBizConstant.GATEWAY_SERVICE_ID);
        req.setServiceIp(InternetUtils.getLocalIp());
        req.setTenantId(log.getTenantId());
        req.setServiceSeq(log.getRefNo());
        String paramCode;
        // 兴安借
        if (BizTypeProducts.getXAJSeriesProducts().contains(log.getProductId())) {
            paramCode = TransBizConstant.XAJ_PAYMENT_ACCT_NO_JD;
        } else {
            paramCode = TransBizConstant.INNER_BANK_CARD;
        }
        SystemParameterRes bankCardRes = systemParameterService.findByParamCode(paramCode,log.getTenantId());
        SystemParameterRes bankNameRes = systemParameterService.findByParamCode(TransBizConstant.INNER_BANK_NANE ,log.getTenantId());
        req.setPayeeAcct(bankCardRes.getParamValue());
        req.setPayeeName(bankNameRes.getParamValue());
        req.setPayerAcct(log.getPayerAccount());
        req.setPayerName(log.getCustomerName());
        req.setPayerCerNo(res.getIdNumber());
        req.setPayerCerType(res.getIdType());
        req.setPayerOpBank(log.getPayerBank());
        req.setPayerPhone(log.getMobile());
        req.setRemark("代收");
        req.setAmnt(log.getAmount().toPlainString());
        req.setCcy(log.getCurrency());
        req.setCustNo(secondLevel.getUserId());
        req.setCustRegTime(DateUtils.format(res.getCreateTime(),"yyyyMMddHHmmss"));
        req.setTransTime(DateUtils.format(log.getLaunchTime(),"yyyyMMddHHmmss"));
        req.setChannelNo(log.getChannel());
        req.setRequestBranchCode(secondLevel.getBankOrgNo());
        // 设置支付协议
        CmCustomerBankcardInfo cmCustomerBankcardInfo = bankCardService.getBankByChannleAndCusIdAndCardNum(log.getCustomerId(),
                log.getChannel(), log.getPayerAccount(), log.getTenantId());
        if(null != cmCustomerBankcardInfo){
            req.setContractNo(cmCustomerBankcardInfo.getContractId());
        }

        List<BankCardRes> bankCardList = bankCardService.getBankCardList(log.getCustomerId(), log.getChannel(), BankCardConstant.STATUS_BANKCARD_1, log.getTenantId());
        List<BankCardRes> collect = bankCardList.stream().filter(card -> TransBizConstant.CARD_TYPE_0.equals(card.getCardType())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(collect)) {
            req.setCreditAcctNo(collect.get(0).getCardNumber());
        }
        String paymentRequest06Json = JsonUtils.toJSon(req);
        return paymentRequest06Json;
    }

    /**
     * 构建代收交易查询请求
     * @param log
     * @return
     * @throws Exception
     */
    @Override
    public String buildQueryTansStatReq(TlPaymentLog log) throws Exception {
        PaymentRequest04 req = new PaymentRequest04();
        req.setServiceId(TransBizConstant.GATEWAY_SERVICE_ID);
        req.setServiceIp(InternetUtils.getLocalIp());
        req.setTenantId(log.getTenantId());
        req.setServiceSeq(SeqUtils.getSN());
        req.setAcctNo(log.getPayerAccount());
        req.setBizType(TransBizConstant.GATEWAY_BIZ_TYPE_02);
        req.setOrigTranNo(log.getRefNo());
        req.setOrigTransTime(DateUtils.format(log.getLaunchTime(),"yyyyMMddHHmmss"));
        String paymentRequest04Json = JsonUtils.toJSon(req);
        return paymentRequest04Json;
    }

    /**
     * 构建单笔代付请求
     *
     * @param log 放款流水
     * @param thirdAcctNo 中间账户
     * @return
     * @throws Exception
     */
    @Override
    public String buildPayReq(TlDisbursementLog log, String thirdAcctNo) throws Exception {
        PaymentRequest05 req = new PaymentRequest05();
        req.setServiceId(TransBizConstant.GATEWAY_SERVICE_ID);
        req.setServiceIp(InternetUtils.getLocalIp());
        req.setTenantId(log.getTenantId());
        req.setServiceSeq(log.getRefNo());
        req.setPayeeAcct(log.getPayeeAccount());
        req.setPayeeName(log.getPayeeName());
        if (StringUtils.isNotBlank(log.getPayeeIdNumber())) {
            req.setPayeeCerNo(log.getPayeeIdNumber());
        }
        req.setPayeeCerType(log.getPayeeIdType());
        req.setPayeeOpBank(log.getPayeeBank());
        if (StringUtils.isNotBlank(log.getMobile())) {
            req.setPayeePhone(log.getMobile());
        }
        SystemParameterRes bankCardRes = systemParameterService.findByParamCode(TransBizConstant.INNER_BANK_CARD
                ,log.getTenantId());
        SystemParameterRes bankNameRes = systemParameterService.findByParamCode(TransBizConstant.INNER_BANK_NANE
                ,log.getTenantId());
        String payerAcctNo = TransBizConstant.YES_FLAG.equals(log.getJointLoanFlag()) ? thirdAcctNo : bankCardRes.getParamValue();
        req.setPayerAcctNo(payerAcctNo);
        req.setPayerName(bankNameRes.getParamValue());
        req.setRemark("代付");
        req.setAmnt(log.getAmount().toPlainString());
        req.setCcy(log.getCurrency());
        req.setTransTime(DateUtils.format(log.getLaunchTime(),"yyyyMMddHHmmss"));
        req.setPayeeAcctType(TransBizConstant.PAYEE_ACCT_TYPE_0);
        req.setChannelNo(log.getChannel());
        // 设置支付协议
        CmCustomerBankcardInfo cmCustomerBankcardInfo = bankCardService.getBankByChannleAndCusIdAndCardNum(log.getCustomerId(),
                log.getChannel(), log.getPayeeAccount(), log.getTenantId());
        if(null != cmCustomerBankcardInfo){
            req.setContractNo(cmCustomerBankcardInfo.getContractId());
        }
        String paymentRequest05Json = JsonUtils.toJSon(req);
        return paymentRequest05Json;
    }

    /**
     * 构建单笔代付查询请求
     * @param log
     * @return
     * @throws Exception
     */
    @Override
    public String buildQueryTansStatReq(TlDisbursementLog log) throws Exception {
        PaymentRequest04 req = new PaymentRequest04();
        req.setServiceId(TransBizConstant.GATEWAY_SERVICE_ID);
        req.setServiceIp(InternetUtils.getLocalIp());
        req.setTenantId(log.getTenantId());
        req.setServiceSeq(SeqUtils.getSN());
        req.setAcctNo(log.getPayeeAccount());
        req.setBizType(TransBizConstant.GATEWAY_BIZ_TYPE_01);
        req.setOrigTranNo(log.getRefNo());
        req.setOrigTransTime(DateUtils.format(log.getLaunchTime(),"yyyyMMddHHmmss"));
        req.setChannelNo(log.getChannel());
        String paymentRequest04Json = JsonUtils.toJSon(req);
        return paymentRequest04Json;
    }

    /**
     * 构建短信请求
     * @param tlSmsLog
     * @param smsContent
     * @return
     * @throws Exception
     */
    @Override
    public String buildSMSRequest(TlSmsLog tlSmsLog, String smsContent) throws Exception {
            SmsRequest02 req = new SmsRequest02();
        req.setServiceId(TransBizConstant.GATEWAY_SERVICE_ID);
        req.setServiceIp(InternetUtils.getLocalIp());
        req.setTenantId(tlSmsLog.getTenantId());
        req.setServiceSeq(tlSmsLog.getSeqNo());
        req.setMobile(tlSmsLog.getMobile());
        req.setContent(smsContent);
        req.setCoCode(tlSmsLog.getOrganizationId());
        String smsRequest02Json = JsonUtils.toJSon(req);
        return smsRequest02Json;
    }

    @Override
    public String buildQuestAvailAmnt(TlPaymentLog log) throws Exception {
        CoreRequest05 req = new CoreRequest05();
        req.setServiceId(TransBizConstant.GATEWAY_SERVICE_ID);
        req.setServiceIp(InternetUtils.getLocalIp());
        req.setTenantId(log.getTenantId());
        req.setServiceSeq(log.getRefNo());
        req.setBaseAcctNo(log.getPayerAccount());
        req.setCcy(log.getCurrency());
        req.setCheckType("2");//是否校验密码 1 检查密码 2 不检查
        String coreRequest05Json = JsonUtils.toJSon(req);
        return coreRequest05Json;
    }

    /**
     * 构建营销信息推送请求
     *
     * @param record 营销信息
     * @return
     */
    @Override
    public String buildMarketSendReq(TlMarketingRecord record) throws Exception{
        EvidenceRequest01 req = new EvidenceRequest01();
        String liveProvince = ""; //居住地址：省
        String liveCity = "";     //居住地址：市
        String liveArea = "";     //居住地址：区
        String workProvince = ""; //工作地址：省
        String workCity = "";     //工作地址：市
        String workArea = "";     //工作地址：区
        String workType = "";     //职业类型
        BigDecimal creditRest = BigDecimal.ZERO; //剩余可用额度

        if(StringUtils.isNotBlank(record.getLiveProvince())){
            PrCodeTable province = codeTableService.findByTypeAndCodeId(TransBizConstant.PROVINCE_TYPE_ID,
                    record.getLiveProvince(), record.getTenantId());
            if(null != province){
                liveProvince = province.getCodeName();
            }
        }
        if(StringUtils.isNotBlank(record.getLiveCity())){
            PrCodeTable city = codeTableService.findByTypeAndCodeId(TransBizConstant.CITY_TYPE_ID,
                    record.getLiveCity(), record.getTenantId());
            if(null != city){
                liveCity = city.getCodeName();
            }
        }
        if(StringUtils.isNotBlank(record.getLiveArea())){
            PrCodeTable area = codeTableService.findByTypeAndCodeId(TransBizConstant.AREA_TYPE_ID,
                    record.getLiveArea(), record.getTenantId());
            if(null != area){
                liveArea = area.getCodeName();
            }
        }
        if(StringUtils.isNotBlank(record.getWorkProvince())){
            PrCodeTable province = codeTableService.findByTypeAndCodeId(TransBizConstant.PROVINCE_TYPE_ID,
                    record.getWorkProvince(), record.getTenantId());
            if(null != province){
                workProvince = province.getCodeName();
            }
        }
        if(StringUtils.isNotBlank(record.getWorkCity())){
            PrCodeTable city = codeTableService.findByTypeAndCodeId(TransBizConstant.CITY_TYPE_ID,
                    record.getWorkCity(), record.getTenantId());
            if(null != city){
                workCity = city.getCodeName();
            }
        }
        if(StringUtils.isNotBlank(record.getWorkArea())){
            PrCodeTable area = codeTableService.findByTypeAndCodeId(TransBizConstant.AREA_TYPE_ID,
                    record.getWorkArea(), record.getTenantId());
            if(null != area){
                workArea = area.getCodeName();
            }
        }
        if(StringUtils.isNotBlank(record.getWorkType())){
            PrCodeTable work = codeTableService.findByTypeAndCodeId(TransBizConstant.INDUSTRY_TYPE_ID,
                    record.getWorkType(), record.getTenantId());
            if(null != work){
                workType = work.getCodeName();
            }
        }
        //授信阶段，剩余可用额度等于授信金额
        if(CustomerConstant.MARKET_STEP_2.equals(record.getStep()) && null != record.getCreditAmount()){
            creditRest = record.getCreditAmount();
        }
        req.setServiceId(TransBizConstant.GATEWAY_SERVICE_ID);
        req.setServiceIp(InternetUtils.getLocalIp());
        req.setTenantId(record.getTenantId());//租户ID
        req.setServiceSeq(record.getSeqNo());
        req.setChannelNo(record.getChannel());//渠道号
        req.setFlowNo(record.getSeqNo());//流水号
        req.setUserId(record.getUserId());//用户Id
        req.setRefereeNo(record.getRecommenderCode());//推荐人编号
        req.setCertNo(record.getIdNumber());//身份证
        req.setMobileNo(record.getMobile());//手机号码
        req.setUserName(record.getChineseName());//客户姓名
        req.setBusType(record.getStep());//进度
        BigDecimal creditAmount = Optional.ofNullable(record.getCreditAmount()).orElse(BigDecimal.ZERO);
        BigDecimal loanAmount = Optional.ofNullable(record.getLoanAmount()).orElse(BigDecimal.ZERO);
        req.setCreditAmnt(creditAmount.setScale(2, BigDecimal.ROUND_DOWN).toPlainString());//授信金额
        req.setLoanAmnt(loanAmount.setScale(2, BigDecimal.ROUND_DOWN).toPlainString());//借款金额
        req.setCreditRest(creditRest.setScale(2, BigDecimal.ROUND_DOWN).toPlainString());//剩余可用额度
        req.setLiveProvince(liveProvince);//居住地址省
        req.setLiveCity(liveCity);//居住地址市
        req.setLiveArea(liveArea);//居住地址区
        req.setLiveDetail(record.getLiveAddress());//居住详细地址
        req.setWorkProvince(workProvince);//工作地址省
        req.setWorkCity(workCity);//工作地址市
        req.setWorkArea(workArea);//工作地址区
        req.setWorkDetail(record.getWorkAddress());//工作地址详细
        req.setOccuptionType(workType);//职业类别
        req.setCompanyName(record.getCompanyName());//公司名称
        req.setTransDate(DateUtils.format(record.getBusinessDate(), DateUtils.DATE_PATTERN_ANOTHER));//交易日期
        req.setTransTime(DateUtils.format(record.getBusinessTime(), DateUtils.PART_DATETIME_PATTERN));//交易时间
        String evidenceRequest01Json = JsonUtils.toJSon(req);
        return evidenceRequest01Json;
    }

    /**
     * 构建营销信息推送结果查询请求
     *
     * @param record 营销信息
     * @return
     */
    @Override
    public String buildMarketCheckReq(TlMarketingRecord record) throws Exception{
        EvidenceRequest02 req = new EvidenceRequest02();
        req.setServiceId(TransBizConstant.GATEWAY_SERVICE_ID);
        req.setServiceIp(InternetUtils.getLocalIp());
        req.setTenantId(record.getTenantId());//租户ID
        req.setServiceSeq(record.getSeqNo());
        req.setChannelNo(record.getChannel());//渠道号
        req.setFlowNo(record.getSeqNo());//流水号
        req.setUserId(record.getUserId());//用户Id
        String evidenceRequest02Json = JsonUtils.toJSon(req);
        return evidenceRequest02Json;
    }

    @Override
    public String buildRefundReq(TlRefundLog log) throws Exception {
        CoreRequest20 req = new CoreRequest20();
        BeanMapping.copy(log,req);
        req.setServiceId(TransBizConstant.GATEWAY_SERVICE_ID);
        req.setServiceIp(InternetUtils.getLocalIp());
        req.setTenantId(log.getTenantId());//租户ID
        req.setServiceSeq(log.getRefNo());
        req.setCustNo(log.getEcifNo());
        req.setSysCd("OTHR");
        req.setCurrency("CNY");
        req.setDebitAndCreditId("DBIT");
        req.setValueDate(DateUtils.formatDate2(log.getBusinessDate()));
        req.setCommissionDate(DateUtils.formatDate2(log.getCommissionDate()));
        req.setCommissionTime(DateUtils.formatDate(log.getCommissiontime(),DateUtils.TIME_PATTERN_ANOTHER));
        req.setAmt(log.getAmount().toPlainString());
        // 兴安花
        req.setModelCode("CC");
        String coreRequest20Json = JsonUtils.toJSon(req);
        return coreRequest20Json;
    }

    /**
     * 构建互转交易服务请求
     *
     * @param log
     * @return
     */
    @Override
    public String buildInterestCompensateReq(TlPaymentLog log) throws Exception {
        CoreRequest16 req = new CoreRequest16();
        req.setServiceId(TransBizConstant.GATEWAY_SERVICE_ID);
        req.setServiceIp(InternetUtils.getLocalIp());
        req.setTenantId(log.getTenantId());
        req.setServiceSeq(log.getRefNo());
        SystemParameterRes transitionalAcctRes = systemParameterService.findByParamCode(TransBizConstant.INNER_TRANSITIONAL_BANK_ACCT, log.getTenantId());
        SystemParameterRes repayAcctRes = systemParameterService.findByParamCode(TransBizConstant.INNER_BANK_REPAY_ACCT, log.getTenantId());
        req.setDebitCcy(TransBizConstant.CURRENCY_CNY);
        req.setCreditCcy(TransBizConstant.CURRENCY_CNY);
        // 互转交易借方金额和贷方金额输其一即可，不要都传
        // req.setCreditAmt(log.getAmount());
        req.setPostScripts(log.getRefNo() + "+" + log.getCustomerId());
        req.setDebitAmt(log.getAmount());
        req.setCreditMediumAcct(repayAcctRes.getParamValue());
        req.setDebitMediumAcct(transitionalAcctRes.getParamValue());
        return JsonUtils.toJSon(req);
    }

    /**
     * 本行卡放款交易
     *
     * @param log
     * @return
     */
    @Override
    public String buildInnerDisbursementReq(TlDisbursementLog log) throws Exception {

        CmCustomerFirstLevel res =customerService.getFirstLevelByCondition(log.getCustomerId(), log.getOrganizationId(),log.getTenantId());
        String refNo = log.getRefNo();
        String loanId = log.getLoanId();
        CoreRequest20 req = new CoreRequest20();
        // 过度阶段是否成功（是否在转到用户卡上的阶段）
        req.setMediumAcctNo(log.getPayerAccount());
        req.setAcctNo(log.getPayerAccount());
        req.setAcctName("放款内部账户过渡户");
        req.setAcctBranch("CN0010001");
        req.setAcctType("");
        req.setToAcctNo(log.getPayeeAccount());
        req.setToAcctName(log.getPayeeName());
        req.setToAcctBranch(log.getPayeeBank());
        req.setToAcctBranchName(log.getPayeeBankName());
        req.setCustNo(res.getEcifId());
        req.setServiceId(TransBizConstant.GATEWAY_SERVICE_ID);
        req.setServiceIp(InternetUtils.getLocalIp());
        req.setTenantId(log.getTenantId());
        req.setServiceSeq(refNo);
        req.setExtBsnId(refNo);
        req.setInstdPty(log.getPayeeBank());
        // 附言
        String remarks = "CCS交易编号:" + refNo + ";" + "借据号:" + loanId;
        // 备注--摘要
        req.setRemarks80(remarks);
        req.setCurrency("CNY");
        // ccs 放款取消接口
        req.setNotifyServiceCode("CDMT004760");
        req.setSysCd("OTHR");
        List<PrCodeTable> codeTables = codeTableService.findListByCodeIds(TransBizConstant.SYS_CD, log.getTenantId());
        if (CollectionUtils.isNotEmpty(codeTables)) {
            req.setSysCd(codeTables.get(0).getCodeId());
        }
        req.setDebitAndCreditId("DBIT");
        req.setValueDate(DateUtils.formatDate2(log.getBusinessDate()));
        req.setCommissionDate(DateUtils.formatDate2(log.getBusinessDate()));
        req.setCommissionTime(DateUtils.formatDate(log.getCreateTime(),DateUtils.TIME_PATTERN_ANOTHER));
        req.setAmt(log.getAmount().toPlainString());
        req.setModelCode("CD");
        // 兴安借




        //CoreRequest16 req = new CoreRequest16();
        /*req.setServiceId(TransBizConstant.GATEWAY_SERVICE_ID);
        req.setServiceIp(InternetUtils.getLocalIp());
        req.setTenantId(log.getTenantId());
        req.setServiceSeq(log.getRefNo());
        req.setDebitCcy(TransBizConstant.CURRENCY_CNY);
        req.setCreditCcy(TransBizConstant.CURRENCY_CNY);
        // 互转交易借方金额和贷方金额输其一即可，不要都传
        // req.setCreditAmt(log.getAmount());
        req.setPostScripts(log.getRefNo() + "+" + log.getCustomerId());
        req.setDebitAmt(log.getAmount());
        // 过渡阶段是否已经成功
        boolean periodFlag = Objects.equals(log.getSumPeriodStatus(), TransBizConstant.DISBURSEMENT_LOG_SUM_STATUS_S);
        req.setDebitMediumAcct(log.getPayerPeriodAccount() : log.getPayerAccount());
        req.setCreditMediumAcct(log.getPayeeAccount() : log.getPayerPeriodAccount());*/
        return JsonUtils.toJSon(req);
    }

    /**
     * 他行卡放款查询
     *
     * @param log
     * @return
     */
    @Override
    public String buildOuterDisbursementReq(TlDisbursementLog log) throws Exception {

        CoreRequest32 req = new CoreRequest32();
        req.setOrgExtReference32(log.getRefNo());
        // todo 确定渠道号
        req.setOrgChannelId("S31");
        req.setNeedFf("");
        req.setServiceId(TransBizConstant.GATEWAY_SERVICE_ID);
        req.setServiceIp(InternetUtils.getLocalIp());
        req.setTenantId(log.getTenantId());
        req.setServiceSeq(log.getRefNo());
        return JsonUtils.toJSon(req);
    }

    /**
     * 构建日终T24核心汇总记账请求
     * @param creditMediumAcctCode 贷方介质账号码值
     * @param seqNo  记账请求流水号
     * @return
     * @throws Exception
     */
    @Override
    public String buildT24Req(DailyAccount record, String creditMediumAcctCode, String seqNo) throws Exception {
        CoreRequest16 req = new CoreRequest16();
        req.setServiceId(TransBizConstant.GATEWAY_SERVICE_ID);
        req.setServiceIp(InternetUtils.getLocalIp());
        req.setTenantId(record.getTenantId());
        req.setServiceSeq(seqNo);
        req.setDebitCcy(TransBizConstant.CURRENCY_CNY);
        req.setCreditCcy(TransBizConstant.CURRENCY_CNY);
        String remarks = "CCS放款交易编号:" + seqNo;
        req.setRemarks80(remarks);
        BigDecimal totalAmount = record.getTotalAmount();
        req.setDebitAmt(totalAmount);
        String creditMediumAcct = systemParameterService.findByParamCode(creditMediumAcctCode, record.getTenantId()).getParamValue();
        String debitMediumAcct = systemParameterService.findByParamCode(TransBizConstant.OUTER_BANK_DISBURSE_PERIOD_ACCT, record.getTenantId()).getParamValue();
        req.setCreditMediumAcct(creditMediumAcct);
        req.setDebitMediumAcct(debitMediumAcct);
        // 取消的金额比当日放款的金额来的大，DC交易账户方向需要互换，且金额必须为正数
        if (BigDecimal.ZERO.compareTo(totalAmount) > 0) {
            remarks = "CCS退汇交易编号:" + seqNo;
            req.setRemarks80(remarks);
            req.setDebitAmt(totalAmount.negate());
            req.setCreditMediumAcct(debitMediumAcct);
            req.setDebitMediumAcct(creditMediumAcct);
        }
        return JsonUtils.toJSon(req);
    }

    @Override
    public String buildQuestAvailBalance(TlPaymentLog log) throws Exception {
        CoreRequest17 req = new CoreRequest17();
        req.setServiceId(TransBizConstant.GATEWAY_SERVICE_ID);
        req.setServiceIp(InternetUtils.getLocalIp());
        req.setTenantId(log.getTenantId());
        req.setServiceSeq(log.getRefNo());
        req.setMediumAcctNo(log.getPayerAccount());
        String coreRequest17Json = JsonUtils.toJSon(req);
        return coreRequest17Json;
    }
}
